package clientSide.javaGui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import static serverSide.Server.*;

import org.json.simple.*;

public class HomePage extends JFrame {
	String serverAddress = "127.0.0.1:5000";
	Image bg;
	
	public HomePage() {
		this.setTitle("Iran Game Center");

		try {
			BufferedImage tmp = ImageIO.read(new File("src/clientSide/javaGui/PIC/HPbackground4.jpg"));
			bg = tmp.getScaledInstance(900, 660, 1);
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.setContentPane(new JComponent() {
			@Override
			protected void paintComponent(Graphics g) {
				g.drawImage(bg,0,0,getParent().getWidth()+15,getParent().getHeight(),
						0,0,getParent().getWidth(),getParent().getHeight(),null);
				super.paintComponent(g);
			}
		});

		this.setLayout(null);
		
		JMenuBar tmpmenuBar = new JMenuBar();
		JMenu tmpMenu = new JMenu("network setting");
		JMenuItem tmpMenuItem = new JMenuItem("change server ip");
		tmpMenuItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				String ans = JOptionPane.showInputDialog(getParent(),new String("Enter server address.\n" + 
						"example  192.168.1.2:4231"),serverAddress);
				if(ans != null)
					serverAddress = ans;
			}
		});
		tmpMenu.add(tmpMenuItem);
		tmpmenuBar.add(tmpMenu);
		this.setJMenuBar(tmpmenuBar);
		
		signinPanel sp = new signinPanel();
		sp.setBounds(30, 30, 250, 110);
		this.add(sp);

		JButton tmpButton = new JButton("Watch concurrent games");
		tmpButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				/**
				 * TODO: concurrent game list
				 */
				System.out.println("concurrent games");
			}
		});
		tmpButton.setBounds(3, 609, 221, 25);
		this.add(tmpButton);

		this.setResizable(false);
		this.setBounds(10,10,915,690);
		this.setVisible(true);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	
	public HomePage(Rectangle r,Image img) {
		this.setTitle("Iran Game Center");

		this.bg = img;
		this.setContentPane(new JComponent() {
			@Override
			protected void paintComponent(Graphics g) {
				g.drawImage(bg,0,0,getParent().getWidth()+15,getParent().getHeight(),
						0,0,getParent().getWidth(),getParent().getHeight(),null);
				super.paintComponent(g);
			}
		});

		this.setLayout(null);
		
		JMenuBar tmpmenuBar = new JMenuBar();
		JMenu tmpMenu = new JMenu("network setting");
		JMenuItem tmpMenuItem = new JMenuItem("change server ip");
		tmpMenuItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				String ans = JOptionPane.showInputDialog(getParent(),new String("Enter server address.\n" + 
						"example  192.168.1.2:4231"),serverAddress);
				if(ans != null)
					serverAddress = ans;
			}
		});
		tmpMenu.add(tmpMenuItem);
		tmpmenuBar.add(tmpMenu);
		this.setJMenuBar(tmpmenuBar);
		
		signinPanel sp = new signinPanel();
		sp.setBounds(30, 30, 250, 110);
		this.add(sp);

		JButton tmpButton = new JButton("Watch concurrent games");
		tmpButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				/**
				 * TODO: concurrent game list
				 */
				System.out.println("concurrent games");
			}
		});
		tmpButton.setBounds(3, 609, 221, 25);
		this.add(tmpButton);

		this.setResizable(false);
		this.setBounds(r);
		this.setVisible(true);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	
	private class signinPanel extends JPanel {
		JTextField username;
		JPasswordField password;
		Socket socket;
		ObjectInputStream reader;
		ObjectOutputStream writer;
		
		public signinPanel() {
			this.setOpaque(false);
			FlowLayout lay = new FlowLayout(FlowLayout.CENTER, 3, 2);
			lay.setAlignOnBaseline(true);
			this.setLayout(lay);
			
			JPanel tmpPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 1, 0));
			JLabel tmpLabel = new JLabel("Username ");
			tmpLabel.setForeground(Color.BLACK);
			tmpPanel.add(tmpLabel);
			username = new JTextField(15);
			tmpPanel.add(username);
			tmpPanel.setPreferredSize(new Dimension(400, 25));
			tmpPanel.setOpaque(false);
			this.add(tmpPanel);
			
			tmpPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 1, 0));
			tmpLabel = new JLabel("Password ");
			tmpLabel.setForeground(Color.BLACK);
			tmpPanel.add(tmpLabel);
			password = new JPasswordField(15);
			tmpPanel.add(password);
			tmpPanel.setPreferredSize(new Dimension(400, 25));
			tmpPanel.setOpaque(false);
			this.add(tmpPanel);
			
			tmpPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 1, 0));
			JButton tmpButton = new JButton("signin");
			tmpButton.setPreferredSize(new Dimension(100,25));
			tmpButton.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					String ip,port;
					try {
						String[] address= serverAddress.split(":");
						ip = address[0];
						port = address[1];
					} catch(Exception ex) {
						JOptionPane.showMessageDialog(getParent().getParent().getParent().getParent(),
								"Server address format is not valid!", "Error",JOptionPane.ERROR_MESSAGE);
						return;
					}
					if(!setUpNetworking(ip, Integer.valueOf(port))) {
						JOptionPane.showMessageDialog(getParent().getParent().getParent().getParent(),
								"Server address is wrong.", "Error",JOptionPane.ERROR_MESSAGE);
						return;
					}
					
					//Set account
					if(!checkSigninInformation(username.getText(), password.getText())) {
						JOptionPane.showMessageDialog(getParent().getParent().getParent().getParent(),
								"Account insformation was wrong.", "Error",JOptionPane.ERROR_MESSAGE);
						return;
					}
					
					HomePage hp = (HomePage)getParent().getParent().getParent().getParent();
					
					new ProfilePage(hp.getBounds(), hp.bg,socket,writer,reader,username.getText());
					hp.dispose();
				}
			});
			tmpPanel.add(tmpButton);
			tmpPanel.setPreferredSize(new Dimension(400, 25));
			tmpPanel.setOpaque(false);
			this.add(tmpPanel);
			
			tmpPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 1, 0));
			tmpButton = new JButton("signup");
			tmpButton.setPreferredSize(new Dimension(100,25));
			tmpButton.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					HomePage hp = (HomePage)getParent().getParent().getParent().getParent();
					
					new SignupPage(hp.getBounds(), hp.bg, hp.serverAddress);
					hp.dispose();
				}
			});
			tmpPanel.add(tmpButton);
			tmpPanel.setPreferredSize(new Dimension(400, 25));
			tmpPanel.setOpaque(false);
			this.add(tmpPanel);
		}
		
		private boolean setUpNetworking(String ip,int port) {
			try {
				socket = new Socket(ip,port);
				reader = new ObjectInputStream(socket.getInputStream());
				writer = new ObjectOutputStream(socket.getOutputStream());
				
				return true;
			} catch(IOException ex) {
				ex.printStackTrace();
				return false;
			}
		}
		
		private boolean checkSigninInformation(String username,String password) {
			JSONObject data = new JSONObject();
			try {
				data.put(SUBJECT_KEY, SUBJECT_VALUE_SIGNIN);
				data.put(SUBJECT_SIGNIN_KEY_USERNAME, username);
				data.put(SUBJECT_SIGNIN_KEY_PASSWORD, password);
				
				writer.writeObject(data);
			} catch(Exception ex) {
				ex.printStackTrace();
				return false;
			}
			try {
				Object obj;
				if((obj = reader.readObject()) != null) {
					data = (JSONObject)obj;
					if((int)data.get(SUBJECT_KEY) == SUBJECT_VALUE_SIGNIN)
						if((int)data.get(SUBJECT_SIGNIN_KEY_ISACCEPTED) == SUBJECT_SIGNIN_VALUE_ACCEPTED)
							return true;
					return false;
				}
			} catch(Exception ex) {
				ex.printStackTrace();
			}
			return false;
		}
	}
	
	public static void main (String[] args) {
		new HomePage();
	}
}
